import { doFetch, getFetch } from '@/utils/doFetch';
import { PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { ColorPicker, Input, message, Space, Tag, theme, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

const defaultColor = [
  '#000000',
  '#000000E0',
  '#000000A6',
  '#00000073',
  '#00000040',
  '#00000026',
  '#0000001A',
  '#00000012',
  '#0000000A',
  '#00000005',
  '#F5222D',
  '#FA8C16',
  '#FADB14',
  '#8BBB11',
  '#52C41A',
  '#13A8A8',
  '#1677FF',
  '#2F54EB',
  '#722ED1',
  '#EB2F96',
  '#F5222D4D',
  '#FA8C164D',
  '#FADB144D',
  '#8BBB114D',
  '#52C41A4D',
  '#13A8A84D',
  '#1677FF4D',
  '#2F54EB4D',
  '#722ED14D',
  '#EB2F964D',
];

const MostTag = ({ max = 20, id }) => {
  const { token } = theme.useToken();
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const inputRef = useRef(null);
  const editInputRef = useRef(null);

  //查询当前项目下的所有标签
  const { data, loading, refresh } = useRequest(
    async () => {
      let res = await getFetch({
        url: '/orgTagTemplate',
        params: {
          orgTagTypeId: id,
        },
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [id],
    },
  );

  // 更新or 删除项目下的标签
  const { run } = useRequest(
    (params) => {
      return doFetch(params);
    },
    {
      manual: true,
      onSuccess: () => {
        refresh();
      },
    },
  );

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [inputValue]);

  const handleClose = (id) => {
    run({ url: `/orgTagTemplate/${id}`, params: {}, method: 'DELETE' });
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (!inputValue || inputValue.replace(/\s/g, '') === '') {
      message.destroy();
      setInputVisible(false);
      return;
    }
    if (inputValue && data?.map((it) => it.name).indexOf(inputValue) === -1) {
      const params = {
        orgTagTypeId: id,
        name: inputValue,
        color: token.colorPrimary,
      };
      run({ url: `/orgTagTemplate`, params: params });
    } else {
      if (inputValue) message.warning('已存在的标签名！');
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleEditInputChange = (e) => {
    setEditInputValue(e.target.value);
  };

  const handleEditInputConfirm = async () => {
    if (!editInputValue || editInputValue.replace(/\s/g, '') === '') {
      message.destroy();
      message.error('标签不可为空字符！');
      return;
    }
    if (
      editInputValue &&
      data
        ?.filter((it, i) => i !== editInputIndex)
        .map((it) => it.name)
        .indexOf(editInputValue) === -1
    ) {
      const newTags = [...data];
      const currentTag = newTags[editInputIndex];

      const params = {
        name: editInputValue,
      };
      run({ url: `/orgTagTemplate/${currentTag?.id}`, params: params, method: 'PUT' });
      setEditInputIndex(-1);
      setInputValue('');
    } else {
      message.warning('已存在的标签名！');
    }
  };

  const tagInputStyle = {
    width: 78,
    verticalAlign: 'top',
  };

  const tagPlusStyle = {
    background: token.colorBgContainer,
    borderStyle: 'dashed',
  };

  return (
    <Space wrap style={{ paddingTop: 4, justifyContent: 'flex-start',gap:8 }}>
      {data?.map?.((tag, index) => {
        if (editInputIndex === index) {
          return (
            <Input
              ref={editInputRef}
              key={tag}
              size="small"
              style={tagInputStyle}
              value={editInputValue}
              onChange={handleEditInputChange}
              onBlur={handleEditInputConfirm}
              onPressEnter={handleEditInputConfirm}
            />
          );
        }
        const isLongTag = tag?.name?.length > 20;
        const tagElem = (
          <Tag
            key={tag.name}
            closable
            style={{
              userSelect: 'none',
              display: 'flex',
              alignItems: 'center',
              paddingLeft: 0,
            }}
            onClose={() => handleClose(tag.id)}
          >
            <ColorPicker
              presets={[
                {
                  label: '预设颜色',
                  colors: defaultColor,
                },
              ]}
              size="small"
              value={tag.color ?? '#000000'}
              onChangeComplete={(val) => {
                const params = {
                  color: val.toHexString(),
                };
                run({ url: `/orgTagTemplate/${tag?.id}`, params: params, method: 'PUT' });
              }}
            ></ColorPicker>
            <span
              style={{ paddingLeft: 4 }}
              onDoubleClick={(e) => {
                setEditInputIndex(index);
                setEditInputValue(tag.name);
                e.preventDefault();
              }}
            >
              {isLongTag ? `${tag.name.slice(0, 20)}...` : tag.name}
            </span>
          </Tag>
        );
        return isLongTag ? (
          <Tooltip title={tag.name} key={tag.name}>
            {tagElem}
          </Tooltip>
        ) : (
          tagElem
        );
      })}
      {inputVisible ? (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={tagInputStyle}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      ) : (
        data?.length < max &&
        editInputIndex === -1 && (
          <Tag style={tagPlusStyle} onClick={showInput}>
            <PlusOutlined /> 新建标签
          </Tag>
        )
      )}
    </Space>
  );
};

export default MostTag;
